/**
 * 测试简单流式请求（不需要工具调用）
 */

const http = require('http');

function testSimpleStream() {
  return new Promise((resolve, reject) => {
    console.log('🔧 测试简单流式请求...');
    
    const postData = JSON.stringify({
      messages: [{ role: 'user', content: '你好' }],
      userId: '00287cfd-f5e2-403e-b78f-b9c327769986'
    });

    const options = {
      hostname: 'localhost',
      port: 5000,
      path: '/api/chat-langchain/stream',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    const req = http.request(options, (res) => {
      console.log(`📡 响应状态: ${res.statusCode}`);
      
      let chunkCount = 0;
      
      res.on('data', (chunk) => {
        chunkCount++;
        const chunkStr = chunk.toString();
        console.log(`📦 第${chunkCount}个chunk:`, chunkStr.substring(0, 200) + (chunkStr.length > 200 ? '...' : ''));
        
        // 尝试解析SSE数据
        const lines = chunkStr.split('\n');
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const jsonData = JSON.parse(line.substring(6));
              console.log(`📄 SSE数据:`, JSON.stringify(jsonData, null, 2));
            } catch (e) {
              console.log(`❌ 解析SSE失败:`, e.message);
            }
          }
        }
      });
      
      res.on('end', () => {
        console.log(`✅ 流式响应完成，共收到${chunkCount}个chunk`);
        resolve({ statusCode: res.statusCode, chunkCount });
      });
      
      res.on('error', (error) => {
        console.log(`❌ 响应流错误:`, error.message);
        reject(error);
      });
    });

    req.on('error', (error) => {
      console.log(`❌ 请求错误:`, error.message);
      reject(error);
    });

    req.on('timeout', () => {
      console.log(`⏰ 请求超时 (10秒)`);
      req.destroy();
      reject(new Error('Request timeout'));
    });

    req.setTimeout(10000); // 10秒超时
    req.write(postData);
    req.end();
  });
}

// 运行测试
async function runTest() {
  console.log('🚀 开始测试简单流式请求...\n');
  
  try {
    await testSimpleStream();
    console.log('\n✨ 测试完成！');
  } catch (error) {
    console.log('\n❌ 测试失败:', error.message);
  }
}

runTest();
